package org.university.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.university.common.ApiResponse;
import org.university.dto.request.PageRequestParams;
import org.university.entity.Student;
import org.university.exception.ResourceNotFoundException;
import org.university.service.StudentService;
import org.university.service.impl.StudentServiceImpl;
import org.university.util.GlobalUtil;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/students")
public class StudentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    // 允许排序的字段白名单
    private static final List<String> ALLOWED_SORT_FIELDS = List.of(
            "studentId", "studentName", "gender",
            "birthDate", "enrollmentDate", "deptId",
            "classId", "phone", "email", "address"
    );
    private final StudentService studentService;
    private final GlobalUtil globalUtil;
    private final StudentServiceImpl studentServiceImpl;

    public StudentController(StudentService studentService, GlobalUtil globalUtil, StudentServiceImpl studentServiceImpl) {
        this.studentService = studentService;
        this.globalUtil = globalUtil;
        this.studentServiceImpl = studentServiceImpl;
    }

    /**
     * 根据ID查询学生
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Student>> getStudentById(@PathVariable String id) {
        return studentService.findById(id)
                .map(ApiResponse::success)
                .orElseThrow(() -> new ResourceNotFoundException("未找到id为: " + id + " 的学生"));
    }

    /**
     * 创建学生
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Student>> createStudent(@RequestBody Student student) {
        Student savedStudent = studentService.save(student);
        return ApiResponse.created(savedStudent);
    }

    /**
     * 更新学生信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Student>> updateStudent(
            @PathVariable String id,
            @RequestBody Student student) {

        if (studentService.findById(id).isEmpty()) {
            throw new ResourceNotFoundException("未找到id为: " + id + " 的学生");
        }
        studentServiceImpl.update(id, student);
        return ApiResponse.success(null);
    }

    /**
     * 删除学生
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable String id) {
        if (studentService.findById(id).isEmpty()) {
            throw new ResourceNotFoundException("未找到id为: " + id + " 的学生");
        }
        studentService.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 多条件查询学生
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<Student>>> searchStudents(
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String studentName,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String birthDate,
            @RequestParam(required = false) String enrollmentDate,
            @RequestParam(required = false) String deptId,
            @RequestParam(required = false) String classId,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String address,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {

        PageRequestParams params = new PageRequestParams(
                ALLOWED_SORT_FIELDS,
                page,
                size,
                sort
        );

        Pageable pageable = globalUtil.buildPageRequest(params);

        Page<Student> result = studentService.searchStudents(
                studentId, studentName, gender, birthDate, enrollmentDate,
                deptId, classId, phone, email, address, pageable);

        return ApiResponse.success(result);
    }
}